#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_RECORDS 1000
#define MAX_CATEGORY_LENGTH 20

enum RecordType {
    INCOME,
    EXPENSE
};
struct Record {
    struct tm timestamp;  //存储于时间相关函数 c库 
    enum RecordType type;  
    float amount;
    char category[MAX_CATEGORY_LENGTH]; // 定义 
}; 

struct Record records[MAX_RECORDS];
int num_records = 0;

//菜单----- 老大 
void displayMenu() {
    printf("\n-----收支账本-----\n");
    printf("1. 添加收支记录\n");
    printf("2. 查看收入记录\n");
    printf("3. 查看支出记录\n");
    printf("4. 查询一段时间内的收支\n");
    printf("5. 查询总余额、收入、支出\n");
    printf("6. 按类别查询收支\n");
    printf("7. 退出\n");
    printf("-----------------------\n");
}

// 将记录保存到文件-------老二 
void saveToFile() {
    FILE *file = fopen("records.txt", "w");
    if (file == NULL) {
        printf("无法打开文件。\n");
        return;
    }
    int i;
    for (i = 0; i < num_records; i++) {
        fprintf(file, "%.2f %d %d %d %d %s\n", records[i].amount, records[i].type, records[i].timestamp.tm_year, records[i].timestamp.tm_mon, records[i].timestamp.tm_mday, records[i].category);
    }

    fclose(file);
    printf("记录已保存到文件。\n");
}

// 从文件中加载记录  ---老大 
void loadFromFile() {
    FILE *file = fopen("records.txt", "r");
    if (file == NULL) {
        printf("无法打开文件。\n");
        return;
    }

    while (fscanf(file, "%f %d %d %d %d %s", &records[num_records].amount, &records[num_records].type, &records[num_records].timestamp.tm_year, &records[num_records].timestamp.tm_mon, &records[num_records].timestamp.tm_mday, records[num_records].category) != EOF) {
        records[num_records].timestamp.tm_year -=0; // 年份需要减去 0
        records[num_records].timestamp.tm_mon -= 0; // 月份是从 1 开始的
        records[num_records].timestamp.tm_hour = 0; // 小时默认为 0
        records[num_records].timestamp.tm_min = 0; // 分钟默认为 0
        records[num_records].timestamp.tm_sec = 0; // 秒数默认为 0
        
        num_records++;
    }   
    fclose(file);
    printf("记录已加载。\n");
}  


// 按日期查询记录---  老二 
void viewRecordsByDateRange() {
    if (num_records == 0) {
        printf("暂无记录。\n");
        return;
    }

    struct tm start_date, end_date;
    printf("请输入起始日期（格式：年 月 日）: ");
    scanf("%d %d %d", &start_date.tm_year, &start_date.tm_mon, &start_date.tm_mday);
    start_date.tm_year -= 0; // 年份需要减去 0
    start_date.tm_mon -= 0; // 月份是从 1 开始的
    start_date.tm_hour = 0; // 小时默认为 0
    start_date.tm_min = 0; // 分钟默认为 0
    start_date.tm_sec = 0; // 秒数默认为 0

    printf("请输入结束日期（格式：年 月 日）: ");
    scanf("%d %d %d", &end_date.tm_year, &end_date.tm_mon, &end_date.tm_mday);
    end_date.tm_year -= 0; // 年份需要减去 0
    end_date.tm_mon -= 0 ; // 月份是从 1 开始的
    end_date.tm_hour = 0; // 小时默认为 0
    end_date.tm_min = 0; // 分钟默认为 0
    end_date.tm_sec = 0; // 秒数默认为 0

    printf("时间\t\t类别\t类型\t金额\n");
    int i;
    for (i = 0; i < num_records; i++) {
        if (difftime(mktime(&records[i].timestamp), mktime(&start_date)) >= 0 && difftime(mktime(&end_date), mktime(&records[i].timestamp)) >= 0) {
            printf("%d-%02d-%02d\t%s\t%s\t%.2f\n", records[i].timestamp.tm_year, records[i].timestamp.tm_mon, records[i].timestamp.tm_mday, records[i].category, (records[i].type == INCOME) ? "收入" : "支出", records[i].amount);
        }
    }
}


// 添加记录--- 陶磊 
void addRecord() {
    if (num_records >= MAX_RECORDS) {
        printf("记录已满，无法添加。\n");
        return;
    }
    struct Record record;
    printf("请输入金额: ");
    scanf("%f", &record.amount);
    getchar(); // 捕获回车键

    printf("请输入类别: ");
    fgets(record.category, MAX_CATEGORY_LENGTH, stdin);
    record.category[strcspn(record.category, "\n")] = 0; // 去除输入字符串的换行符

    printf("请选择记录类型 (1 - 收入, 2 - 支出): ");
    int type_choice;
    scanf("%d", &type_choice);
    getchar(); // 捕获回车键	  
    if (type_choice == 1) {
        record.type = INCOME;
    } else if (type_choice == 2) {
        record.type = EXPENSE;
    } else {
        printf("无效的记录类型。\n");
        return;
    }
    printf("请输入记录日期（格式：年 月 日）: ");
    scanf("%d %d %d", &record.timestamp.tm_year, &record.timestamp.tm_mon, &record.timestamp.tm_mday);
    record.timestamp.tm_year -= 0; // 年份需要减去 0
    record.timestamp.tm_mon -= 0; // 月份是从 1 开始的
    record.timestamp.tm_hour = 0; // 小时默认为 0
    record.timestamp.tm_min = 0; // 分钟默认为 0
    record.timestamp.tm_sec = 0; // 秒数默认为 0

    records[num_records] = record;
    num_records++;

    printf("记录添加成功！\n");
    
	saveToFile(); // 添加记录后立即保存到文件

    num_records++;
    
}

// 查询总记录 ---老三 
void viewTotalBalance() {
    if (num_records == 0) {
        printf("暂无记录。\n");
        return;
    }

    float total_income = 0;
    float total_expense = 0;

    int i;
    for (i = 0; i < num_records; i++) {
        if (records[i].type == INCOME) {
            total_income += records[i].amount;
        } else {
            total_expense += records[i].amount;
        }
    }

    printf("总收入: %.2f\n", total_income);
    printf("总支出: %.2f\n", total_expense);
    printf("总余额: %.2f\n", total_income - total_expense);
}

// 查看收入or支出记录-----老三 
void viewRecords(enum RecordType type) {
    if (num_records == 0) {
        printf("暂无记录。\n");
        return;
    }

    printf("时间\t\t类别\t金额\n");
    int i;
    for (i = 0; i < num_records; i++) {
        if (records[i].type == type) {
            printf("%d-%02d-%02d\t%s\t%.2f\n", records[i].timestamp.tm_year, records[i].timestamp.tm_mon, records[i].timestamp.tm_mday, records[i].category, records[i].amount);
        }
    }
}

// 按类别查询记录
// 按类别查询收支记录-------老二 
void viewRecordsByCategory(char* search_category) {
    if (num_records == 0) {
        printf("暂无记录。\n");
        return;
    }

    printf("时间\t\t类型\t金额\n");
    int i;
    for (i = 0; i < num_records; i++) {
        if (strcmp(records[i].category, search_category) == 0) {
            printf("%d-%02d-%02d\t%s\t%.2f\n", records[i].timestamp.tm_year, records[i].timestamp.tm_mon, records[i].timestamp.tm_mday, (records[i].type == INCOME) ? "收入" : "支出", records[i].amount);
        }
    }
}

// 主函数---老大 
int main() {
    // 加载记录
    loadFromFile();
    int choice;
    do {
        displayMenu();
        printf("请选择操作: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                addRecord();
                break;
            case 2:
                viewRecords(INCOME);
                break;
            case 3:
                viewRecords(EXPENSE);
                break;
            case 4:
                viewRecordsByDateRange();
                break;
            case 5:
                viewTotalBalance();
                break;
            case 6:
    		{
        		char search_category[MAX_CATEGORY_LENGTH];
        		printf("请输入要查询的类别: ");
        		getchar(); // 捕获输入缓冲区中的换行符
        		fgets(search_category, MAX_CATEGORY_LENGTH, stdin);
        		search_category[strcspn(search_category, "\n")] = 0; // 去除输入字符串的换行符
        		viewRecordsByCategory(search_category);
        		break;
    		}
            case 7:
                printf("退出程序。\n");
                break;
            default:
                printf("无效的选项，请重新输入。\n");
                break;
        }
    } while (choice != 7);

    return 0;
}

